<template>
  <div class="order-management">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="已取消" :value="2" />
            <el-option label="已发货" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已退货" :value="5" />
            <el-option label="退货中" :value="6" />
            <el-option label="已评价" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="支付宝" value="alipay" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 搜索条件标签 -->
    <div class="search-tags" v-if="hasSearchConditions">
      <span class="search-tags-label">搜索条件：</span>
      <el-tag 
        v-if="searchForm.status !== null" 
        closable 
        @close="clearSearchStatus"
        class="search-tag"
      >
        订单状态：{{ getStatusName(searchForm.status) }}
      </el-tag>
      <el-tag 
        v-if="searchForm.paymentMethod" 
        closable 
        @close="clearSearchPaymentMethod"
        class="search-tag"
      >
        支付方式：{{ getPaymentMethodName(searchForm.paymentMethod) }}
      </el-tag>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="订单ID" width="100" />
      <el-table-column prop="orderNo" label="订单号" width="180" />
      <el-table-column prop="actualAmount" label="支付金额" width="120">
        <template #default="{ row }">
          ¥{{ row.actualAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
          <el-button 
            v-if="row.status === 1"
            type="success" 
            link 
            @click="handleDeliver(row)"
          >
            发货
          </el-button>
          <el-button 
            v-if="row.status === 6"
            type="warning" 
            link 
            @click="handleReturn(row)"
          >
            确认退货
          </el-button>
          <el-button 
            v-if="[0, 1].includes(row.status)"
            type="danger" 
            link 
            @click="handleCancel(row)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialogVisible"
      width="800px"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单ID">{{ currentOrder.id }}</el-descriptions-item>
            <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(currentOrder.status)">
                {{ getStatusName(currentOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="支付金额">¥{{ currentOrder.actualAmount }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h3>商品信息</h3>
          <el-table :data="currentOrder.orderItems" border>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="productImage" label="商品图片" width="100">
              <template #default="{ row }">
                <el-image 
                  v-if="row.productImage"
                  :src="row.productImage" 
                  :preview-src-list="[row.productImage]"
                  fit="cover"
                  style="width: 50px; height: 50px;"
                />
                <span v-else>暂无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价">
              <template #default="{ row }">¥{{ row.price }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="subtotal" label="小计" width="120">
              <template #default="{ row }">¥{{ row.subtotal }}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getOrderList, 
  getOrderDetail, 
  cancelOrder,
  deliverOrder,
  returnOrder 
} from '@/api/order'

// 搜索表单
const searchForm = reactive({
  status: null,
  paymentMethod: null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 订单详情
const detailDialogVisible = ref(false)
const currentOrder = ref(null)

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    0: '未支付',
    1: '已支付',
    2: '已取消',
    3: '已发货',
    4: '已完成',
    5: '已退货',
    6: '退货中',
    7: '已评价'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'danger',
    3: 'primary',
    4: 'success',
    5: 'danger',
    6: 'warning',
    7: 'success'
  }
  return typeMap[status] || 'info'
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const methodMap = {
    'wechat': '微信支付',
    'alipay': '支付宝'
  }
  return methodMap[method] || '未知方式'
}

// 判断是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.status !== null || 
         searchForm.paymentMethod !== null
})

// 获取订单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getOrderList({
      status: searchForm.status,
      paymentMethod: searchForm.paymentMethod,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.code === 1) {
      const { records, total: totalCount } = res.data
      tableData.value = records
      total.value = totalCount
    } else {
      ElMessage.error(res.msg || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const res = await getOrderDetail(row.id)
    currentOrder.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 发货
const handleDeliver = (row) => {
  ElMessageBox.confirm('确认发货该订单吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deliverOrder(row.id)
        if (res.code === 1) {
          ElMessage.success('发货成功')
          getList()
        } else {
          ElMessage.error(res.msg || '发货失败')
        }
      } catch (error) {
        console.error('发货失败:', error)
        ElMessage.error('发货失败')
      }
    })
    .catch(() => {})
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm('确认取消该订单吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await cancelOrder(row.id)
        if (res.code === 1) {
          ElMessage.success(res.data || '取消成功')
          getList()
        } else {
          ElMessage.error(res.msg || '取消订单失败')
        }
      } catch (error) {
        console.error('取消订单失败:', error)
        ElMessage.error('取消订单失败')
      }
    })
    .catch(() => {})
}

// 确认退货
const handleReturn = (row) => {
  ElMessageBox.confirm('确认该订单退货吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await returnOrder(row.id)
        if (res.code === 1) {
          ElMessage.success('确认退货成功')
          getList()
        } else {
          ElMessage.error(res.msg || '确认退货失败')
        }
      } catch (error) {
        console.error('确认退货失败:', error)
        ElMessage.error('确认退货失败')
      }
    })
    .catch(() => {})
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.status = null
  searchForm.paymentMethod = null
  handleSearch()
}

// 清除搜索条件
const clearSearchStatus = () => {
  searchForm.status = null
  handleSearch()
}

const clearSearchPaymentMethod = () => {
  searchForm.paymentMethod = null
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.order-management {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-tags {
  margin-bottom: 20px;
}

.search-tags-label {
  margin-right: 8px;
  color: #606266;
}

.search-tag {
  margin-right: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  padding: 0 20px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  margin-bottom: 16px;
  font-weight: 500;
  color: #303133;
}
</style> 